package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.CodeUtil;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.vo.user.InviteCodeVo;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.appserver.utils.StringUtils;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.cssw.fyzb.busi.cache.CacheKeys.forVerify;
import static com.cssw.fyzb.busi.util.Bizs.*;

/**
 * 新增用户
 *
 * @author Feng Chen
 */
@Function(description = "新增用户", parameters = {
        @Parameter(name = "inviteCode", type = Type.String, description = "邀请码", required = true),
        @Parameter(name = "verifyCode", type = Type.Integer, description = "验证码", required = true),
        @Parameter(name = "mobile", type = Type.String, description = "手机号码", required = true),
        @Parameter(name = "loginPwd", type = Type.String, description = "登录密码", required = true),
        @Parameter(name = "tradePwd", type = Type.String, description = "交易密码", required = false),
//        @Parameter(name = "imsi", type = Type.String, description = "设备标识", required = true)
})
@Component
public class Register implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private SimpleCache simpleCache;

    private static final Logger logger = LoggerFactory.getLogger(Register.class);

    @Override
    public Response execute(Request request) throws Exception {
        String inviteCode = request.getString("inviteCode");
        String mobile = request.getString("mobile");
        String loginPwd = request.getString("loginPwd");
        String tradePwd = request.getString("tradePwd");
        String verifyCode = request.getString("verifyCode");
        String cached = simpleCache.get(forVerify(mobile));

//        if (tradePwd == null || !Pattern.compile("\\d{6}").matcher(tradePwd).matches()) {
//            return Response.fail(ERROR_FORMAT_TRADE_PWD.message, ERROR_FORMAT_TRADE_PWD.code);
//        }
        if (loginPwd == null || loginPwd.length() < 6 || loginPwd.length() > 18) {
            return Response.fail(ERROR_FORMAT_LOGIN_PWD.message, ERROR_FORMAT_LOGIN_PWD.code);
        }

        if (!judgeContainsStr(loginPwd)) {
            return Response.fail("登录密码必须包含字母");
        }

        try {
            User inviter = null;
            Long userId = null;
            if (org.apache.commons.lang.StringUtils.isNotEmpty(inviteCode)) {
                userId = CodeUtil.decode(inviteCode);
                inviter = userService.getById(userId);
                if (inviter == null) {
                    return Response.fail(ERROR_INVITCODE.message, ERROR_INVITCODE.code);
                }
                User user = userService.getById(userId);
                InviteCodeVo inviteCodeVo = new InviteCodeVo();
                //判断是否实名
                if (user.getFaceAuth().equals("0")) {
                    return Response.fail("推荐人未实名");
                }
            } else {
                return Response.fail(ERROR_INVITCODE.message, ERROR_INVITCODE.code);
            }

            if (userService.getByMobile(mobile) != null) {
                return Response.fail(ERROR_REGISTERED.message, ERROR_REGISTERED.code);
            }

            // 校验验证码
            if (!verifyCode.equals(cached)) {
                return Response.fail(ERROR_VERIFY.message, ERROR_VERIFY.code);
            }

            // 保存用户
            userService.save(userId, mobile, loginPwd, null);
            // 删除内存中的验证码
            simpleCache.delete(forVerify(mobile));
            Map data = new HashMap();
            data.put("userId", userId);
            return Response.success().put("data", data);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("新增用户失败");
        }
    }

    public boolean judgeContainsStr(String name) {
        String regex = ".*[a-zA-Z]+.*";
        Matcher m = Pattern.compile(regex).matcher(name);
        return m.matches();
    }


}
